import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: xiaotutu
 * Date: 2025-01-06
 * Time: 17:45
 */
public class JDBCDemo1 {
    public static void main(String[] args) throws SQLException {
        // 假定数据库中有一个student表 (id, name) 往里面插入一个数据

        //1. 创建数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");

        //2. 和数据库服务器建立连接
        Connection connection = dataSource.getConnection();

        //3. 构造 SQL语句
        String sql = "insert into student values (1, '张三')";
        PreparedStatement statement = connection.prepareStatement(sql);

        //4. 执行SQL语句  返回值就是这次操作影响到几行
        int n = statement.executeUpdate();
        System.out.println("n = " + n);

        //5. 释放必要的资源 关闭连接
        statement.close();
        connection.close();
    }
}
